package com.lz.sports.adapter

import com.lz.library.adapter.BindingAdapter
import com.lz.sports.BR
import com.lz.sports.LogUtils
import com.lz.sports.R
import com.lz.sports.bean.ExamInspect
import com.lz.sports.bean.Examinee
import com.lz.sports.bean.Inspect

//检录适配器
class InspectAdapter(list: List<Inspect>) : BindingAdapter<Inspect>(list) {

    //上一次选中的项
    private var preInspect: Inspect? = null

    companion object {

        fun newInspectAdapter(size: Int): InspectAdapter {
            val list = ArrayList<Inspect>()
            for (i in 0 until size) {
                list.add(Inspect(i + 1))
            }
            return InspectAdapter(list).apply { if (itemCount > 0) clickItem(0) }
        }
    }

    override fun getLayoutResId(viewType: Int): Int = R.layout.item_inspect

    override fun getVariableId(viewType: Int): Int = BR.inspect

    fun clickItem(position: Int) {
        preInspect?.unselect()
        preInspect = getItem(position).apply { select() }
    }

    fun next() {
        for (index in 0 until data.size) {
            if (!data[index].hasExaminee()) {
                clickItem(index)
                break
            }
        }
    }

    fun hasInspected(): Boolean {
        for (index in 0 until data.size) {
            if (data[index].hasExaminee()) {
                return true
            }
        }
        return false
    }

    fun clear() {
        LogUtils.i("clear...")
        data.forEach { it.reset() }
        if (itemCount > 0) clickItem(0)
    }

    fun addExamInspect(inspect: ExamInspect) {
        for (index in 0 until data.size) {
            if (data[index].isSelected) {
                data[index].joinExamInspect(inspect)
                break
            }
        }
    }

    //考生是否已经加入在列表中
    fun hasExamInspect(inspect: ExamInspect): Boolean {
        for (index in 0 until data.size) {
            if (data[index].hasInspect(inspect)) return true
        }
        return false
    }

    //考生是否已经加入在列表中
    fun hasExaminee(examinee: Examinee): Boolean {
        for (index in 0 until data.size) {
            if (data[index].hasExaminee(examinee)) return true
        }
        return false
    }



    fun inspectExamineeList(): List<ExamInspect> = ArrayList<ExamInspect>().apply {
        data.forEach { inspect -> inspect.examInspect()?.also { add(it) } }
    }
}